//
//  SSegmentedView.m
//  EasyRetail
//
//  Created by Samuel on 6/12/15.
//
//

#import "SSegmentedView.h"

@implementation SSegmentedView
{
    NSMutableArray *getTitleArray;
    UIView *lines;
}

- (id)initWithFrame:(CGRect)frame
{
    if ((self = [super initWithFrame:frame]))
    {
//        [self commonInitWithFrame:frame];
    }
    return self;
}
- (void)setDelegate:(NSObject<SSegmentedDelegate> *)delegate
{
    _delegate = delegate;
    
    getTitleArray = [[NSMutableArray alloc]initWithArray:[self.delegate SSegmentedView:self]];
    float btnWight = self.frame.size.width/[getTitleArray count];
    self.layer.masksToBounds= YES;
    self.layer.cornerRadius = 3;
    
    for (int i=0;i<[getTitleArray count];i++) {
        NSString*getTitle = [getTitleArray objectAtIndex:i];
        UIButton *toPickBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [toPickBtn setTitle:getTitle forState:UIControlStateNormal];
        [toPickBtn.titleLabel setFont:[UIFont systemFontOfSize:12]];
        [toPickBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [toPickBtn setBackgroundColor:[UIColor whiteColor]];
        [toPickBtn setTag:i];
        [toPickBtn addTarget:self action:@selector(didtoPickBtn:) forControlEvents:UIControlEventTouchDown];
        [toPickBtn setFrame:CGRectMake(i*btnWight, 0, btnWight, self.frame.size.height)];
        [self addSubview:toPickBtn];
    }
    
    
    lines = [[UIView alloc]initWithFrame:CGRectMake(0, self.frame.size.height-2, btnWight, 2)];
    [lines setBackgroundColor:[UIColor redColor]];
    [self addSubview:lines];
}
- (void)didtoPickBtn:(UIButton*)sender
{
    [UIView animateWithDuration:.2 animations:^{
        [lines setCenter:CGPointMake(sender.center.x, lines.center.y)];
    }];
    if (self.delegate && [self.delegate respondsToSelector:@selector(SSegmentedView:didSelectRowAtIndex:)] )
    {
        [self.delegate SSegmentedView:self didSelectRowAtIndex:sender.tag];
    }

    
}
- (void)SSegmentedViewDidSelectRowAtIndex:(NSInteger)index;
{
    for (id obj in self.subviews)  {
        if ([obj isKindOfClass:[UIButton class]]) {
            UIButton* theButton = (UIButton*)obj;
            if (theButton.tag == index) {
//                 [self didtoPickBtn:theButton];
                [UIView animateWithDuration:.2 animations:^{
                    [lines setCenter:CGPointMake(theButton.center.x, lines.center.y)];
                }];
            }
        }
    }
}
- (void)SSegmentedViewSwapSelectRowAtIndex:(NSInteger)index;
{
    for (id obj in self.subviews)  {
        if ([obj isKindOfClass:[UIButton class]]) {
            UIButton* theButton = (UIButton*)obj;
            if (theButton.tag == index) {
                [self didtoPickBtn:theButton];

            }
        }
    }
}
@end
